package com.ml.mall.service.variant.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ml.mall.bean.req.product.*;
import com.ml.mall.bean.req.product.vo.*;
import com.ml.mall.bean.req.variant.*;
import com.ml.mall.bean.req.variant.vo.SysProductVariantSalesVO;
import com.ml.mall.bean.req.variant.vo.VariantEditSkuDataVO;
import com.ml.mall.bean.req.variant.vo.VariantNewSkuDataVO;
import com.ml.mall.bean.req.variant.vo.VariantRecommendVO;
import com.ml.mall.bean.res.product.*;
import com.ml.mall.bean.res.variant.SysProductVariantQueryAllRes;
import com.ml.mall.bean.res.variant.SysProductVariantQueryCartRes;
import com.ml.mall.bean.res.variant.SysProductVariantQueryOneRes;
import com.ml.mall.bean.vo.coupon.CouponVo;
import com.ml.mall.bean.vo.coupon.UsableCouponVo;
import com.ml.mall.bean.vo.variant.SysProductVariantSalesVo;
import com.ml.mall.bean.vo.variant.VariantDetailVO;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.consts.UserRoleTypeConsts;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.deduct.SysADeduct;
import com.ml.mall.entity.product.SysProduct;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.entity.variant.*;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.enums.SysSeqNameEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.mapper.variant.SysProductVariantMapper;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.common.CommonSeqService;
import com.ml.mall.service.company.SysCompanyService;
import com.ml.mall.service.coupon.SysCouponService;
import com.ml.mall.service.deduct.SysADeductService;
import com.ml.mall.service.product.SysProductService;
import com.ml.mall.service.shop.ShopService;
import com.ml.mall.service.tax.TaxService;
import com.ml.mall.service.variant.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.mall.utils.OrderPriceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.ml.mall.utils.SpringUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* <p>
    *  服务实现类
    * </p>
*
* @author kyyang
* Created 2021-05-15
*/
@Slf4j
@Service
public class SysProductVariantServiceImpl extends ServiceImpl<SysProductVariantMapper, SysProductVariant> implements SysProductVariantService {

    @Autowired
    private  SysProductVariantMapper  sysProductVariantMapper;

    @Autowired
    private CommonSeqService commonSeqService;

    @Autowired
    private SysProductVariantSkuService sysProductVariantSkuService;

    @Autowired
    private SysProductVariantPicService sysProductVariantPicService;

    @Autowired
    private SysProductVariantSalesService sysProductVariantSalesService;

    @Autowired
    private TaxService taxService;

    @Autowired
    private SysADeductService sysADeductService;

    @Autowired
    private SysProductVariantRecommendService sysProductVariantRecommendService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    private SysProductVariantDescripService sysProductVariantDescripService;

    @Lazy
    @Autowired
    private SysProductService sysProductService;

    @Lazy
    @Autowired
    private ShopService shopService;

    @Lazy
    @Autowired
    private SysCouponService sysCouponService;


    @Override
    public SysProductVariant sysTimeBeforeMoney(String timeEnd, Long variantId) {
        return sysProductVariantMapper.selectTimeBeforeData(variantId,timeEnd);
    }

    @Override
    public VariantDetailVO sysProductVariantQueryRele(Long variantId) {
        return sysProductVariantMapper.selectRelationDetail(variantId);
    }

    @Override
    @Transactional
    public int sysProductVariantNew(VariantNewReq req) {
        //更新产品数量
        Date date = new Date();
        Long vid = commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_VARIANT_ID.getCode(),7);
        QueryWrapper<SysCompany> q1 = new QueryWrapper<>();
        q1.eq("company_id",req.getSupplierId());
        SysCompany sysCompany = sysCompanyService.getOne(q1);
        SysProductVariant entity = new SysProductVariant();
        SpringUtil.copyPropertiesIgnoreNull(req,entity);
        entity.setVariantId(vid);
        entity.setEffectDt(date);
        entity.setExpiryDt(new Date(CommonConsts.MAX_EXPIRY_TIME));
        entity.setVerId(0);
        SysProduct sysProduct = sysProductService.selectByProductId(req.getProductId());
        if(sysProduct==null){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        entity.setCategoryId(sysProduct.getCategoryId());
        //默认未审核
        entity.setVerifyStatus(0);
        entity.setSearchKeyWord(req.getKeyword());
        //判断keyword是否包含变体名字
        if(req.getKeyword() != null){
            if(entity.getSearchKeyWord().indexOf(entity.getVariantName())==-1){
                entity.setSearchKeyWord(entity.getSearchKeyWord()+"||"+entity.getVariantName());
            }
        }
        //查询售价
        BigDecimal price = req.getPrice();
        entity.setPrice(price);
        //传入为百分比 需要除100
        BigDecimal CommissionRate=null;
        if(null != entity.getCommissionRate() && entity.getCommissionRate().compareTo(BigDecimal.ZERO)>0){
            CommissionRate=entity.getCommissionRate().divide(BigDecimal.valueOf(100));
        }
        entity.setCommissionRate(CommissionRate);
        entity.setSaleNum(0);
        int state=0;
        if(sysProduct.getState().intValue() != 3){
            state=sysProduct.getState().intValue();
        }
        entity.setState(state);
        int i = sysProductVariantMapper.insert(entity);

        //图片信息
        List<ProductPicNewVO> picArr = req.getPicUrlArr();
        if(picArr!=null&&picArr.size()>0){
            List<SysProductVariantPic> list = new ArrayList<>();
            for(ProductPicNewVO p:picArr){
                SysProductVariantPic sysProductVariantPic = new SysProductVariantPic();
                BeanUtils.copyProperties(p,sysProductVariantPic);
                sysProductVariantPic.setProductId(req.getProductId());
                sysProductVariantPic.setVariantId(vid);
                list.add(sysProductVariantPic);
            }
            sysProductVariantPicService.saveBatch(list);
        }
        //描述信息
        String desc=req.getDescription();
        if(null != desc && !"".equals(desc)){
            SysProductVariantDescrip sysProductVariantDescrip=new SysProductVariantDescrip();
            sysProductVariantDescrip.setDescrip(desc);
            sysProductVariantDescrip.setVariantId(vid);
            sysProductVariantDescrip.setIndex(0);
            sysProductVariantDescripService.save(sysProductVariantDescrip);
        }
        //规格信息
        VariantNewSkuDataVO skuDate = req.getSkuData();
        if(skuDate!=null){
            SysProductVariantSku sysProductVariantSku = new SysProductVariantSku();
            BeanUtils.copyProperties(skuDate,sysProductVariantSku);
            sysProductVariantSku.setVariantId(vid);
            sysProductVariantSkuService.save(sysProductVariantSku);
        }
        SysProductVariantSalesVo sysProductVariantSalesVO = req.getSysProductVariantSales();
        if(null != sysProductVariantSalesVO && !sysProductVariantSalesVO.equals(new SysProductVariantSalesVo())  ){
            sysProductVariantSalesService.saveSysProductVariantSales(sysProductVariantSalesVO,null,vid,0);
        }
        return i;
    }

    @Override
    @Transactional
    public int sysProductVariantEdit(VariantEditReq req) {
        UpdateWrapper<SysProductVariant> sysProductVariantUpdateWrapper = new UpdateWrapper<>();
        sysProductVariantUpdateWrapper.eq("id",req.getId());
        SysProductVariant sysProductVariant = sysProductVariantMapper.selectById(req.getId());
        Date date = new Date();
        SysProductVariant entity = new SysProductVariant();
        int verId;
        //价格或者提成比变动则增加变动记录
        boolean bl=false;
        if((req.getCommissionRate()==null && sysProductVariant.getCommissionRate() != null) || (req.getCommissionRate() != null && sysProductVariant.getCommissionRate() == null)){
            bl=true;
        }else {
            if(req.getCommissionRate() != null && sysProductVariant.getCommissionRate() != null){
                if (req.getPrice().compareTo(sysProductVariant.getPrice()) != 0 || req.getCommissionRate().compareTo(sysProductVariant.getCommissionRate().multiply(BigDecimal.valueOf(100))) != 0){
                    bl=true;
                }
            }
        }
        if(bl){
            entity.setExpiryDt(date);
            entity.setState(2);
            sysProductVariantMapper.update(entity,sysProductVariantUpdateWrapper);
            sysProductVariant.setId(null);
            req.setId(null);
            //避免 ID 问题 根据 variantId 查询当前 最大
            verId = getProductVerId(sysProductVariant.getVariantId())+1;
        }else {
            verId = getProductVerId(sysProductVariant.getVariantId());
        }
        SpringUtil.copyPropertiesIgnoreNull(req,sysProductVariant);

        //查询售价
        BigDecimal price = req.getPrice();
        entity.setPrice(price);
        //传入为百分比 需要除100
        BigDecimal CommissionRate=null;
        if(null != req.getCommissionRate() && req.getCommissionRate().compareTo(BigDecimal.ZERO)>0){
            CommissionRate=req.getCommissionRate().divide(BigDecimal.valueOf(100));
        }
        sysProductVariant.setCommissionRate(CommissionRate);
        sysProductVariant.setVerId(verId);
        sysProductVariant.setTitle(req.getDescription());
        sysProductVariant.setSearchKeyWord(req.getKeyword());
        //判断keyword是否包含变体名字
        if(req.getKeyword() != null){
            if(sysProductVariant.getSearchKeyWord().indexOf(sysProductVariant.getVariantName())==-1){
                sysProductVariant.setSearchKeyWord(sysProductVariant.getSearchKeyWord()+"||"+sysProductVariant.getVariantName());
            }
        }
        sysProductVariant.setEffectDt(date);
        sysProductVariant.setExpiryDt(new Date(CommonConsts.MAX_EXPIRY_TIME));
        //判断是否为修改
        int i=0;
        if (null == sysProductVariant.getId()){
            i = sysProductVariantMapper.insert(sysProductVariant);
        }else {
            i = sysProductVariantMapper.updateById(sysProductVariant);
        }

        //图片信息
        List<ProductPicEditVO> picArr = req.getPicUrlArr();
        //删除实体关联的所有图片
        QueryWrapper<SysProductVariantPic> wrapper =  new QueryWrapper<>();
        wrapper.eq("variant_id",sysProductVariant.getVariantId());
        sysProductVariantPicService.remove(wrapper);
        if(picArr!=null&&picArr.size()>0){
            List<SysProductVariantPic> list = new ArrayList<>();
            for(ProductPicEditVO p:picArr){
                SysProductVariantPic sysProductVariantPic = new SysProductVariantPic();
                BeanUtils.copyProperties(p,sysProductVariantPic);
                sysProductVariantPic.setProductId(sysProductVariant.getProductId());
                sysProductVariantPic.setVariantId(sysProductVariant.getVariantId());
                list.add(sysProductVariantPic);
            }
            boolean k=sysProductVariantPicService.saveBatch(list);
        }
        //描述
        String desc=req.getDescription();
        QueryWrapper<SysProductVariantDescrip> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("variant_id",req.getVariantId());
        SysProductVariantDescrip one = sysProductVariantDescripService.getOne(queryWrapper);
        if(null == desc || "".equals(desc)){
            if(one != null){
                sysProductVariantDescripService.removeById(one.getId());
            }
        }else {
            if(one != null){
                one.setDescrip(desc);
                boolean f= sysProductVariantDescripService.updateById(one);
            }else {
                SysProductVariantDescrip sysProductVariantDescrip=new SysProductVariantDescrip();
                sysProductVariantDescrip.setDescrip(desc);
                sysProductVariantDescrip.setVariantId(req.getVariantId());
                sysProductVariantDescrip.setIndex(0);
                sysProductVariantDescripService.save(sysProductVariantDescrip);
            }
        }
        //规格信息
        VariantNewSkuDataVO skuDate = req.getSkuData();
        if(skuDate!=null){
            SysProductVariantSku sysProductVariantSku = new SysProductVariantSku();
            SpringUtil.copyPropertiesIgnoreNull(skuDate,sysProductVariantSku);
            sysProductVariantSku.setVariantId(req.getVariantId());
            UpdateWrapper<SysProductVariantSku> w2 = new UpdateWrapper<>();
            w2.eq("variant_id",sysProductVariant.getVariantId());
            if(null != skuDate.getId() && 0L!=skuDate.getId()){
                sysProductVariantSkuService.update(sysProductVariantSku,w2);
            }else {
                sysProductVariantSkuService.save(sysProductVariantSku);
            }

        }

        if(req.getRecommendObj()!=null){
            VariantRecommendVO recommendObj = req.getRecommendObj();
            UpdateWrapper<SysProductVariantRecommend> upw = new UpdateWrapper<>();
            upw.eq("variant_id",sysProductVariant.getVariantId());
            if(recommendObj.getAdminRecommend()!=null){
                upw.set("admin_recommend",recommendObj.getAdminRecommend()) ;
            }
            if(recommendObj.getLatestRecommend()!=null){
                upw.set("latest_recommend",recommendObj.getLatestRecommend());
            }
            if(recommendObj.getPopularRecommend()!=null){
                upw.set("popular_recommend",recommendObj.getPopularRecommend());
            }
            boolean p=sysProductVariantRecommendService.update(upw);
        }

        if(null != req.getSysProductVariantSales() && !req.getSysProductVariantSales().equals(new SysProductVariantSalesVo())) {
            if (null != req.getSysProductVariantSales().getId() && 0L != req.getSysProductVariantSales().getId()) {
                //检测是否为修改
                Boolean flag = sysProductVariantSalesService.checkSalesByUpdate(req.getSysProductVariantSales());
                if(flag){
                    UpdateWrapper<SysProductVariantSales> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("expiry_dt", new Date());
                    updateWrapper.set("state",0);
                    updateWrapper.eq("id", req.getSysProductVariantSales().getId());
                    sysProductVariantSalesService.update(updateWrapper);
                }
                if (sysProductVariantSalesService.checkSales(req.getSysProductVariantSales())) {
                    if (flag){
                        //添加
                        SysProductVariantSales byId = sysProductVariantSalesService.getById(req.getSysProductVariantSales().getId());
                        sysProductVariantSalesService.saveSysProductVariantSales(req.getSysProductVariantSales(), byId.getPromoId(), req.getVariantId(), byId.getVerId() + 1);
                    }else {
                        //修改
                        SysProductVariantSales sysProductVariantSales=new SysProductVariantSales();
                        SpringUtil.copyPropertiesIgnoreNull(req.getSysProductVariantSales(),sysProductVariantSales);
                        sysProductVariantSalesService.updateById(sysProductVariantSales);
                    }

                }
            } else {
                if (null != req.getSysProductVariantSales() && req.getSysProductVariantSales() != new SysProductVariantSalesVo()) {
                    sysProductVariantSalesService.saveSysProductVariantSales(req.getSysProductVariantSales(), null, req.getVariantId(), 0);
                }
            }
        }
        return i;
    }

    private int getProductVerId(Long variantId) {
       int max = sysProductVariantMapper.selectMaxVerId(variantId);
        return max;
    }

    @Override
    @Transactional
    public int sysProductVariantDel(List<Long> ids) {
        return sysProductVariantMapper.deleteBatchIds(ids);
    }

    @Override
    public SysProductVariantQueryOneRes sysProductVariantByQueryOne(VariantQueryOneReq variantQueryOneReq) {
        SysProductVariantQueryOneRes sysProductVariantQueryOneRes = new SysProductVariantQueryOneRes();
        //查询 sku 信息
        QueryWrapper<SysProductVariant> w2 = new QueryWrapper<>();
        w2.eq("variant_id",variantQueryOneReq.getVariantId());
        w2.eq("expiry_dt",new Date(CommonConsts.MAX_EXPIRY_TIME));
        SysProductVariant sysProductVariant = sysProductVariantMapper.selectOne(w2);
        if(variantQueryOneReq.getIsComparison() == 1){ //是对比 则计算提成之后的价格
            SysADeduct curDeduct = sysADeductService.getCurDeduct();
            sysProductVariant.changePrice(curDeduct);
        }
        if(sysProductVariant!=null){
            SpringUtil.copyPropertiesIgnoreNull(sysProductVariant,sysProductVariantQueryOneRes);
            sysProductVariantQueryOneRes.setKeyword(sysProductVariant.getSearchKeyWord());
            //显示为百分比*100 需要在计算价格之前
            BigDecimal CommissionRate=new BigDecimal(0);
            if(sysProductVariant.getCommissionRate() != null){
                CommissionRate=sysProductVariant.getCommissionRate().multiply(BigDecimal.valueOf(100));
            }
            sysProductVariantQueryOneRes.setCommissionRate(CommissionRate);
            QueryWrapper<SysProductVariantDescrip> descripQueryWrapper = new QueryWrapper<>();
            descripQueryWrapper.eq("variant_id",variantQueryOneReq.getVariantId());
            SysProductVariantDescrip descrip = sysProductVariantDescripService.getOne(descripQueryWrapper);
            sysProductVariantQueryOneRes.setDescrip(descrip.getDescrip());
            log.info("getProductId==={}",sysProductVariant.getProductId());
            //brand信息
            if(null != sysProductVariant.getProductId()){
                QueryWrapper<SysProduct> sysProductQueryWrapper=new QueryWrapper<>();
                sysProductQueryWrapper.eq("product_id",sysProductVariant.getProductId());
                SysProduct one = sysProductService.getOne(sysProductQueryWrapper);
                sysProductVariantQueryOneRes.setBrand(one.getBrand());
            }
        }
        //描述信息
        VariantEditSkuDataVO variantEditSkuDataVO = new VariantEditSkuDataVO();
        QueryWrapper<SysProductVariantDescrip> descripQueryWrapper=new QueryWrapper<>();
        descripQueryWrapper.eq("variant_id",variantQueryOneReq.getVariantId());
        SysProductVariantDescrip descrip = sysProductVariantDescripService.getOne(descripQueryWrapper);
        if(null != descrip){
            sysProductVariantQueryOneRes.setDescription(descrip.getDescrip());
        }
        //查询sku规格
        QueryWrapper<SysProductVariantSku> wapper = new QueryWrapper<>();
        wapper.eq("variant_id",variantQueryOneReq.getVariantId());
        SysProductVariantSku one1 = sysProductVariantSkuService.getOne(wapper);
        if(one1!=null){
            SpringUtil.copyPropertiesIgnoreNull(one1,variantEditSkuDataVO);
            BigDecimal stock=new BigDecimal(one1.getStock());
            variantEditSkuDataVO.setStock(stock);
            BigDecimal lowstock=new BigDecimal(one1.getLowStock());
            variantEditSkuDataVO.setLowStock(lowstock);
        }
        sysProductVariantQueryOneRes.setSkuData(variantEditSkuDataVO);

        //查询图片
        QueryWrapper<SysProductVariantPic> queryWrapper = new QueryWrapper();
        queryWrapper.eq("variant_id",variantQueryOneReq.getVariantId());
        List<SysProductVariantPic> list = sysProductVariantPicService.list(queryWrapper);
        if(list!=null&&list.size()>0){
            List<ProductPicEditVO> pics = new ArrayList<>();
            for(SysProductVariantPic sysProductVariantPic:list){
                ProductPicEditVO vo = new ProductPicEditVO();
                BeanUtils.copyProperties(sysProductVariantPic,vo);
                pics.add(vo);
            }
            sysProductVariantQueryOneRes.setPicUrlArr(pics);
        }

        //查询 sku 限时促销
        QueryWrapper<SysProductVariantSales> wrapper = new QueryWrapper<>();
        wrapper.eq("variant_id",variantQueryOneReq.getVariantId());
        wrapper.eq("expiry_dt",new Date(CommonConsts.MAX_EXPIRY_TIME));
        wrapper.eq("state",1);
        //Date date = new Date();
        /*wapper.ge("begin_time",date);
        wapper.lt("end_time",date);*/
        SysProductVariantSales one = sysProductVariantSalesService.getOne(wrapper);
        SysProductVariantSalesVO sysProductVariantSalesVO = new SysProductVariantSalesVO();
        if(one!=null){
            BeanUtils.copyProperties(one,sysProductVariantSalesVO);
            sysProductVariantSalesVO.setSellPrice(one.getPrice());
        }
        sysProductVariantQueryOneRes.setSysProductVariantSales(sysProductVariantSalesVO);
        return sysProductVariantQueryOneRes;
    }

    @Override
    public List<SysProductVariantQueryAllRes> sysProductVariantQueryAll(VariantQueryAllReq variantQueryAllReq) {
        List<SysProductVariantQueryAllRes> list = sysProductVariantMapper.selectVariantByProduct(variantQueryAllReq.getProductId());
        return list;
    }

    @Override
    @Transactional
    public int sysProductVariantSalesNew(VariantSalesNewReq req) {
        Long prompId = commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_PROMO_ID.getCode(),8);
        SysProductVariantSales sysProductVariantSales = new SysProductVariantSales();
        BeanUtils.copyProperties(req,sysProductVariantSales);
        sysProductVariantSales.setPromoId(prompId);
        sysProductVariantSales.setVerId(1);
        sysProductVariantSales.setEffectDt(new Date());
        //失效日期 2099-12-31 00:00:00
        sysProductVariantSales.setExpiryDt(new Date(CommonConsts.MAX_EXPIRY_TIME));
        boolean save = sysProductVariantSalesService.save(sysProductVariantSales);
        return save?1:0;
    }

    @Override
    @Transactional
    public int sysProductVariantSalesEdit(VariantSalesEditReq req) {
        Date date = new Date();
        SysProductVariantSales byId = sysProductVariantSalesService.getById(req.getId());
        SysProductVariantSales sales = new SysProductVariantSales();
        //sales.setId(byId.getId());
        sales.setExpiryDt(date);
        UpdateWrapper<SysProductVariantSales> sysProductVariantSalesUpdateWrapper = new UpdateWrapper<>();
        sysProductVariantSalesUpdateWrapper.eq("expiry_dt",new Date(CommonConsts.MAX_EXPIRY_TIME));
        sysProductVariantSalesService.update(sales,sysProductVariantSalesUpdateWrapper);
        SpringUtil.copyPropertiesIgnoreNull(req,byId);
        byId.setId(null);
        byId.setVerId(byId.getVerId()+1);
        byId.setEffectDt(date);
        byId.setExpiryDt(new Date(CommonConsts.MAX_EXPIRY_TIME));
        boolean save = sysProductVariantSalesService.save(byId);
        return save?1:0;
    }

    @Override
    public BigDecimal findSkuPriceByVariantId(Long variantId) {

        QueryWrapper<SysProductVariant> wrapper = new QueryWrapper<>();
        wrapper.eq("variant_id",variantId);
        wrapper.eq("expiry_dt",new Date(CommonConsts.MAX_EXPIRY_TIME));
        SysProductVariant sysProductVariant = sysProductVariantMapper.selectOne(wrapper);
        if(sysProductVariant == null){
            return BigDecimal.ZERO;
        }
        BigDecimal price = sysProductVariant.getPrice()==null?BigDecimal.ZERO:sysProductVariant.getPrice();
        BigDecimal taxRate = BigDecimal.ZERO;
        //不包含税
        if(sysProductVariant.getIncludTax()==1){
            taxRate = price.multiply(taxService.getCurTax());
        }
        SysADeduct curDeduct = sysADeductService.getCurDeduct();
        BigDecimal deduct = price.multiply(curDeduct.getDeductRate());

        price.add(taxRate).add(OrderPriceUtils.getOrderPriceByCentType(curDeduct.getCentType(),deduct));
        return price;
    }


    @Override
    public com.ml.mall.bean.page.Page<SysProductShopPageRes> sysProductQueryByKeywordAndStates(ShopQueryPageByKeyWord dto) {

        List<SysProductShopPageRes> resList = sysProductVariantMapper.queryProductVariant(dto);
        if (resList == null){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        //重新调整售价
        //重新根据提成比例设置售价
        SysADeduct curDeduct = sysADeductService.getCurDeduct();
        resList.stream().forEach(item->{
            item.changePrice(curDeduct);
        });
        //查询条数
        Integer total = sysProductVariantMapper.queryProductVariantExistsCounts(dto);
        List<SysProductShopPageRes> shopPageResList = shopService.recognizeShopHaveCoupponPageRes(resList);
        com.ml.mall.bean.page.Page<SysProductShopPageRes> pageRes = new com.ml.mall.bean.page.Page<>(dto.getPageIndex(),dto.getPageNum());
        //排序
        List<SysProductShopPageRes> newList = sortByPrice(shopPageResList, dto.getSortType());
        pageRes.setTotal(total);
        pageRes.setRecords(newList);
        return pageRes;
    }

    @Override
    public com.ml.mall.bean.page.Page<SysProductShopPageRes> sysProductQueryPageByCategoryId(ShopQueryPageByCategoryIdDto dto) {
        //0升，1降
        List<SysProductShopPageRes> listItem = sysProductVariantMapper.queryVariantByCategoryId(dto);
        if (listItem==null){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        //分页查询总数量
        Integer total = sysProductVariantMapper.queryVariantNumByCategoryId(dto);
        List<SysProductShopPageRes> shopPageResList = shopService.recognizeShopHaveCoupponPageRes(listItem);
        //重新根据提成比例设置售价
        SysADeduct curDeduct = sysADeductService.getCurDeduct();
        listItem.stream().forEach(item->{
            item.changePrice(curDeduct);
        });
        //排序
        List<SysProductShopPageRes> newList = sortByPrice(listItem, dto.getSortType());
        com.ml.mall.bean.page.Page<SysProductShopPageRes> pageRes = new com.ml.mall.bean.page.Page<>(dto.getPageIndex(),dto.getPageNum());
        pageRes.setTotal(total);
        pageRes.setRecords(newList);
        return pageRes;
    }

    @Override
    public List<SysProductQueryByRandomWith18Res> sysProductQueryByRandomWith18(QueryRandom18Dto dto) {
        //随机查询<=18条存在促销的数据返回
        List<SysProductQueryByRandomWith18Res> listItem = sysProductVariantMapper.queryVariantByRandomWith18(dto);
        if (listItem==null){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        //重新根据提成比例设置售价
        SysADeduct curDeduct = sysADeductService.getCurDeduct();
        listItem.stream().forEach(item->{
            item.changePrice(curDeduct);
        });
        List<SysProductQueryByRandomWith18Res> shopPageListRes = shopService.recognizeShopHaveCoupponPageRandom18Res(listItem);
        //排序
        List<SysProductQueryByRandomWith18Res> newList=null;
        if (dto.getSortType()==0){
            newList =shopPageListRes.stream().sorted(Comparator.comparing(SysProductQueryByRandomWith18Res::getPrice)).collect(Collectors.toList());
        }else {
            newList =shopPageListRes.stream().sorted(Comparator.comparing(SysProductQueryByRandomWith18Res::getPrice).reversed()).collect(Collectors.toList());
        }
        return newList;
    }

    @Override
    public SysProductVariants sysProductQueryOneByVariantId(VariantIdDto dto) {
        SysProductVariants backData = new SysProductVariants();
        //查产品
        SysProduct product = sysProductVariantMapper.selectProductByVariantId(dto.getVariantId());
        //查公司
        QueryWrapper<SysCompany> q1 = new QueryWrapper<>();
        q1.eq("company_id",product.getSupplierId());
        SysCompany sysCompany = sysCompanyService.getOne(q1);
        //查询产品下的全部变体
        List<ProductVariantShopVO> productVariantShopVOS = sysProductVariantMapper.selectVariantByProductId(product.getProductId());
        SysADeduct curDeduct = sysADeductService.getCurDeduct();
        for (ProductVariantShopVO vo:productVariantShopVOS){
            vo.changePrice(curDeduct);
            CouponVo couponVo = new CouponVo();
            couponVo.setSupplierId(vo.getSupplierId());
            couponVo.setVariantId(vo.getVariantId());
            List<UsableCouponVo> usableCouponVos = sysCouponService.queryUsableCoupon(couponVo);
            vo.setCouponArr(usableCouponVos);
        }
        //查需要返回的数据
        BeanUtils.copyProperties(product,backData);
        backData.setSupplierCode(sysCompany.getInviteCode());
        backData.setVariantArr(productVariantShopVOS);
        return backData;
    }

    @Override
    public com.ml.mall.bean.page.Page<SysProductShopPageRes> sysProductQueryPageBySupplierId(ShopQueryPageBySupplierIdDto dto) {
        //0升，1降
        List<SysProductShopPageRes> listItem = sysProductVariantMapper.queryVariantBySupplierId(dto);
        if (listItem==null){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        //重新根据提成比例设置售价
        SysADeduct curDeduct = sysADeductService.getCurDeduct();
        listItem.stream().forEach(item->{
            item.changePrice(curDeduct);
        });
        //分页查询总数量
        Integer total = sysProductVariantMapper.queryVariantNumBySupplierId(dto);
        List<SysProductShopPageRes> shopPageResList = shopService.recognizeShopHaveCoupponPageRes(listItem);
        com.ml.mall.bean.page.Page<SysProductShopPageRes> pageRes = new com.ml.mall.bean.page.Page<>(dto.getPageIndex(),dto.getPageNum());
        //排序
        List<SysProductShopPageRes> newList = sortByPrice(shopPageResList, dto.getSortType());

        pageRes.setTotal(total);
        pageRes.setRecords(newList);
        return pageRes;
    }

    @Override
    public List<SysProductShopPageRes> sysProductQueryRandom12ByVariantId(SysVariantIdDto dto) {
        //查询该variantId下的categoryId
        String categoryId = sysProductVariantMapper.sysCategoryIdByVariantId(dto);
        //根据categoryId来随机查询12条返回数据
        List<SysProductShopPageRes> listItem = sysProductVariantMapper.sys12VariantByCategoryId(categoryId);
        //重新根据提成比例设置售价
        SysADeduct curDeduct = sysADeductService.getCurDeduct();
        listItem.stream().forEach(item->{
            item.changePrice(curDeduct);
        });
        List<SysProductShopPageRes> shopPageResList = shopService.recognizeShopHaveCoupponPageRes(listItem);
        return shopPageResList;
    }

    @Override
    public int sysProductVariantStateEdit(VariantStateEditReq req) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        QueryWrapper<SysProductVariant> queryWrapper = new QueryWrapper<>();
        int i=0;
        if(null != req.getId() && req.getId() != 0){
            queryWrapper.eq("variant_id",req.getId());
            queryWrapper.eq("expiry_dt",new Date(CommonConsts.MAX_EXPIRY_TIME));
            SysProductVariant sysProductVariant = sysProductVariantMapper.selectOne(queryWrapper);
            if(null == sysProductVariant){
                throw new BizException(CommonEnum.SELECT_ERROR);
            }
            //判断产品状态是否是开启 开启则可以修改
            QueryWrapper<SysProduct> wrapper = new QueryWrapper<>();
            wrapper.eq("product_id",sysProductVariant.getProductId());
            SysProduct one = sysProductService.getOne(wrapper);
            if(null == one){
                throw new BizException(CommonEnum.SELECT_ERROR);
            }
            if(one.getState() != 1){
                throw new BizException(CommonEnum.PRDUCT_STATE_ERROR);
            }
            int state=req.getState();
            if(UserRoleTypeConsts.ROLE_TYPE_1 != currentUser.getRoleType().intValue()){
                if(state == 0 && state != sysProductVariant.getState().intValue()){
                    throw new BizException(CommonEnum.UPDATE_PRODUCT_STATE_ERROR);
                }
            }
            sysProductVariant.setState(state);
            i=sysProductVariantMapper.updateById(sysProductVariant);
        }
        return i;
    }

    @Override
    public SysProductVariantQueryCartRes getSysProductVariant(Long id) {
        return sysProductVariantMapper.getSysVariantRes(id);
    }

    public List<SysProductShopPageRes> sortByPrice(List<SysProductShopPageRes> list,Integer type){
        //排序
        List<SysProductShopPageRes> newList=null;
        if (type==0){
            newList =list.stream().sorted(Comparator.comparing(SysProductShopPageRes::getPrice)).collect(Collectors.toList());
        }else {
            newList =list.stream().sorted(Comparator.comparing(SysProductShopPageRes::getPrice).reversed()).collect(Collectors.toList());
        }
        return newList;
    }
}
